﻿namespace SampleSite.admin
{
    using GenericHtml;
    using System;
    using System.Linq;
    using System.Web.Security;
    using WLFramework.Data.Linq;
    using WLFramework.Security;
    using WLFramework.Validation;
    using WLFramework.Web;

    public partial class login : System.Web.UI.Page
    {
        private class LoginUser
        {
            [Required]
            public string Name { get; set; }

            [Required]
            public string Password { get; set; }

            [Required]
            public string Code { get; set; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsPostBack)
            {
                LoginUser user;
                var errors = this.Context.GetModel<LoginUser>(out user);
                if (errors.Count == 0)
                {
                    var tuple = this.Session["loginCode"] as Tuple<string, DateTime>;
                    if (tuple == null ||
                       (DateTime.Now - tuple.Item2).TotalMinutes > 2)
                    {
                        this.Response.AlertErrorMessage("验证码失效");
                        return;
                    }

                    if (string.Compare(tuple.Item1, user.Code, true) != 0)
                    {
                        this.Response.AlertErrorMessage("验证码错误");
                        return;
                    }

                    if (Login(user.Name, user.Password))
                    {
                        FormsAuthentication.SetAuthCookie(user.Name, false);
                        this.Response.Redirect("~/admin/");
                    }
                    else
                    {
                        this.Response.AlertErrorMessage("账号或密码错误!");
                    }
                }
            }
        }

        private bool Login(string name, string password)
        {
            using (PermissionContext db = new PermissionContext())
            {
                MD5Hash md5 = new MD5Hash();
                md5.Update(password);
                byte[] binary = md5.HashBytes;
                var user = (from p in db.sys_User
                            where p.U_LoginNO == name &&
                                  p.U_Password == binary &&
                                  p.U_State == 1
                            select new Tuple<sys_User, sys_UserInfo>(
                                    p, p.sysUserInfosysUsers.FirstOrDefault())).FirstOrDefault();

                if (user != null &&
                    user.Item1 != null && user.Item2 != null)
                {
                    this.Session["current_user"] = new UserInfo
                    {
                        U_ID = user.Item1.U_ID,
                        U_CName = user.Item2.U_CName,
                    };

                    if (Context.Request.ServerVariables["HTTP_VIA"] != null)
                    {
                        user.Item1.U_LastIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
                                                     .ToString();
                    }
                    else
                    {
                        user.Item1.U_LastIP = Request.ServerVariables["REMOTE_ADDR"]
                                                     .ToString();
                    }

                    user.Item1.U_LastLoginTime = DateTime.Now;

                    db.sys_User.Where(k => k.U_ID == user.Item1.U_ID)
                               .Set(k => k.U_LastIP, user.Item1.U_LastIP)
                               .Set(k => k.U_LastLoginTime, user.Item1.U_LastLoginTime)
                               .Update();

                    return true;
                }
            }

            return false;
        }
    }
}